package org.goldfish.cookied_chatroom02.model;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.goldfish.cookied_chatroom02.dao.DaoManager;
import org.goldfish.cookied_chatroom02.entity.RegisteringUserBean;
import org.goldfish.cookied_chatroom02.entity.UserBean;
import org.goldfish.cookied_chatroom02.utils.Utils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.InputStream;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RegisterManagerImpl implements RegisterManager {
    @NotNull
    public static Map<String, String> getFormContentMap(InputStream stream) {
        try {
            return Utils.parseFormPostInputStream(stream);
        }catch (Exception e){
            return new HashMap<>();
        }
    }
    @Override
    public UserBean getUserBeanFromSession(HttpSession session) {
        Object name_raw = session.getAttribute(NAME);
        if (name_raw == null) return null;
        Object password_raw = session.getAttribute(PASSWORD);
        if (password_raw == null) return null;
        UserBean bean = new UserBean();
        bean.setName(name_raw.toString());
        bean.setPassword(password_raw.toString());
        return bean;
    }

    @NotNull
    @Override
    public UserBean getUserBeanFromPostInputStream(InputStream stream) {
        Map<String, String> postMap = getFormContentMap(stream);
        UserBean bean = validateNameAndPassword(postMap);
        if (bean instanceof RegisteringUserBean) {
            //this only happens if there is problem with the info provided
            return bean;
        }
        String verify = postMap.get(VERIFY);
        if (verify == null || verify.isEmpty())
            return new RegisteringUserBean(new Exception("请验证密码"));
        if (!verify.equals(bean.getPassword()))
            return new RegisteringUserBean(new Exception("两次密码不一致"));
        return bean;
    }

    protected UserBean validateNameAndPassword(Map<String, String> map) {
        String name = map.get(NAME);
        if (name == null || name.isEmpty())
            return new RegisteringUserBean(new Exception("请输入用户名"));
        String password = map.get(PASSWORD);
        if (password == null || password.isEmpty())
            return new RegisteringUserBean(new Exception("请输入密码"));
        UserBean bean = new UserBean();
        bean.setName(name);
        bean.setPassword(password);
        return bean;
    }

    @Override
    @Nullable
    public UserBean getUserBeanFromCookies(Cookie[] cookies) {
        if (cookies == null) return null;
        String name = null;
        String password = null;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(NAME)) {
                name = cookie.getValue();
            } else if (cookie.getName().equals(PASSWORD)) {
                password = cookie.getValue();
            }
        }
        if (name == null) return null;
        if (password == null) return null;
        UserBean bean = new UserBean();
        bean.setName(name);
        bean.setPassword(password);
        return bean;
    }

    @Override
    public boolean writeUserBeanToCookie(@NotNull HttpServletResponse response,@NotNull UserBean userBean) {
        String name = userBean.getName();
        if (name == null) return false;
        String password = userBean.getPassword();
        if (password == null) return false;
        Cookie nameCookie=new Cookie(NAME, name);
        nameCookie.setMaxAge(60 * 60 * 24 * 7);
        Cookie passwordCookie=new Cookie(PASSWORD, password);
        passwordCookie.setMaxAge(60 * 60 * 24 * 7);
        response.addCookie(nameCookie);
        response.addCookie(passwordCookie);
        return true;

    }

    @Override
    public boolean writeUserBeanToDB(@NotNull UserBean userBean) {
        if (userBean == null)
            return false;
        String SQL = "select * from user where name=?";
        Object[] bindArgs = {userBean.getName()};
        List<List<Object>> set = DaoManager.getInstance().query(SQL, bindArgs);
        if (set == null) return false;
        if (!set.isEmpty()) return false;

        try {
            SQL = "insert into user(name,password) values(?,?)";
            bindArgs = new Object[]{userBean.getName(), userBean.getPassword()};
            System.out.println(SQL);
            return 1 == DaoManager.getInstance().update(SQL, null, bindArgs);
        } catch (SQLException e) {
            return false;
        }

    }

    @Override
    public void warnOverwriteExistingUser(HttpServletResponse response, UserBean userBean) {

    }

    @Override
    public void warn(String message, @NotNull HttpServletRequest request) {
        Utils.warn(message, request);
    }

    @Override
    @Nullable
    public RequestDispatcher register(HttpServletRequest request) {
        return request.getRequestDispatcher("/pages/register.jsp");
    }

    @Override
    @Nullable
    public RequestDispatcher login(HttpServletRequest request) {
        return request.getRequestDispatcher("/pages/login.jsp");
    }
}
